package com.mes.controller.manu;

import com.mes.entity.User;
import com.mes.service.manu.ManuFacilitiesDataService;
import com.yy.base.common.dao.Dao;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import com.yy.base.util.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("manuFacilitiesDataController")
public class ManuFacilitiesDataController {

	public static final String[] KEYS = new String[]{"DATA1","DATA2","DATA3","DATA4","DATA5","DATA6","DATA7","DATA8","DATA9","DATA10",
			"DATA11","DATA12","DATA13","DATA14","DATA15","DATA16","DATA17","DATA18","DATA19","DATA20"};

	@Autowired
	private Dao dao;
	@Autowired
	private ManuFacilitiesDataService manuFacilitiesDataService;


	//通过工序ID，设备ID获取当前工序设备下配置的采集点保存当前实时采集的数据，并返回保存数据的主键ID
	@ResponseBody
	@RequestMapping("getData")
	public Message getData(HttpServletRequest request){
		Message msg = new Message();
		User user = (User)request.getSession().getAttribute(UserUtil.USERSESSION);
		String pageId = request.getParameter("pageId");//数据采集按钮ID
		String batchId = request.getParameter("batchId");
		String sql = "select Emes_Facilities_Id from Emeso_Manu_Batch_Process where Emes_Facilities_Id is not null and Emeso_Manu_Batch_Id = ?";
		Map<String, Object> data = dao.queryUnique(sql, batchId);
		
		String processId = request.getParameter("processId");
		String facId = null;
		
		if (data != null) {
			facId = (String)data.get("EMES_FACILITIES_ID");
		} else {
			facId = request.getParameter("facId");
		}
		if (facId == null) {
			msg.setErrorMessage("此随工单还未关联生产设备！");
			return msg;
		}
		
		sql = "select Emeso_Manu_Batch_Process_Id from Emeso_Manu_Batch_Process where EMES_PROCESS_ID = ? and Emeso_Manu_Batch_Id = ?";
		data = dao.queryUnique(sql, processId, batchId);
		if (data == null) {
			msg.setErrorMessage("此工序还未开工！");
			return msg;
		}
		String batchProcessId = (String)data.get("EMESO_MANU_BATCH_PROCESS_ID");
		sql = "select did.table_name  SAVE_TABLE," +
                "       idd.column_name SAVE_COLUMN," +
                "       efdp.FULLNAME," +
                "       efdp.NEW_VALUE," +
                "       efdp.NEW_TIME " +
                "  from Emes_DC_Input_Data        DID " +
                "       join Emes_DC_Input_Data_Detail idd on DID.EMES_DC_INPUT_DATA_ID = IDD.EMES_DC_INPUT_DATA_ID " +
                "       join Emeso_DC_Item             di on idd.emeso_dc_item_id = di.emeso_dc_item_id " +
                "       left join emes_facilities_dc_point  efdp on di.name = efdp.name and efdp.emes_facilities_id = ? " +
                " where  did.Emes_DC_Input_Data_id = ?";
		//查询出当前工序的设备下所有的采集点信息
		List<Map<String,Object>> list = dao.query(sql, facId, pageId);
		if(list != null && list.size() > 0){
			List<Object> params = new ArrayList<Object>();//参数值列表
			String uuid = StringUtil.getUUID();
			sql = "INSERT INTO SAVE_TABLE (EMESO_MANU_PROCESS_DATA_ID, EMES_PROCESS_ID, EMES_FACILITIES_ID,Emeso_Manu_Batch_Process_Id,EMES_DC_INPUT_DATA_ID,";
			String sqlValues = " values('" + uuid + "', ?, ?,?,?,";
			params.add(processId);
			params.add(facId);
			params.add(batchProcessId);
			params.add(pageId);

			String tableName = String.valueOf(list.get(0).get("SAVE_TABLE"));
			//遍历采集到的实时数据并保存
			String updateSql = "update Emes_DC_Input_Data_Detail set last_value=? where Emes_DC_Input_Data_id=? and COLUMN_NAME=?";
			for (int i = 0; i < list.size(); i++) {
				Map<String,Object> tmpMap = list.get(i);
				Object dataValue = tmpMap.get("NEW_VALUE");
				if(dataValue != null){
					String save_column = String.valueOf(tmpMap.get("SAVE_COLUMN"));
					sql += save_column+"," ;
					sqlValues += "?,";
					params.add(dataValue);
					dao.executeSql(updateSql,dataValue,pageId,save_column);//更新最后一次的录入值
				}
			}

			sql += "AD_ORG_ID, AD_CLIENT_ID, CREATED, CREATEDBY, UPDATED, UPDATEDBY)" ;

			//得到配置中表名，替换到SQL中
			sql = sql.replace("SAVE_TABLE", tableName);
			sqlValues += "?, ?, sysdate, ?, sysdate, ?)";
			params.add(user.getOrgId());
			params.add(user.getClientId());
			params.add(user.getId());
			params.add(user.getId());
			int row = dao.executeSql(sql + sqlValues, params.toArray());

			if(row > 0) {
				msg.put("ID", uuid);//返回保存的数据ID
				msg.setOkMessage("数据采集成功！");
			} else {
				msg.setErrorMessage("数据采集失败！");
			}
		}
		return msg;
	}

	@ResponseBody
	@RequestMapping("getDataHistroy")
	public Message getDataHistroy(HttpServletRequest request){
		Message msg = new Message();
		String pageId = request.getParameter("pageId");
		String batchId = request.getParameter("batchId");
		String processId = request.getParameter("processId");
		String pageCode = request.getParameter("pageCode");
		final String order = " asc "; //排序方式决定后面前后行值的设置和默认值的设置
		Map<String,Object> mapSql = manuFacilitiesDataService.emesoJobOrderKey(pageCode);
		List<Map<String, Object>> dataList = dao.query(mapSql.get("SQL").toString());

		/*for(int i=0;i<dataList.size()-1;i++){
			Map<String, Object> curMap = dataList.get(i);
			Map<String,Object> preMap = dataList.get(i+1);
			if("asc".equals(StringUtils.trim(order))) {
				for(String key : KEYS){
					preMap.put("PRE_"+key,curMap.get(key));
				}
				preMap.put("PRE_TIMESTAMP",curMap.get("TIMESTAMP"));	//毫秒数  精确到秒
				preMap.put("PRE_MINU",curMap.get("MINU"));	//毫秒数  精确到分钟
			} else {
				for(String key : KEYS){
					curMap.put("PRE_"+key,preMap.get(key));
				}
				curMap.put("PRE_TIMESTAMP",preMap.get("TIMESTAMP"));	//毫秒数  精确到秒
				curMap.put("PRE_MINU",preMap.get("MINU"));	//毫秒数  精确到分钟
			}
		}*/

		String sql = "select did.Emes_DC_Input_Data_id,di.code,idd.name,did.table_name SAVE_TABLE,idd.column_name SAVE_COLUMN,di.data_type," +
				"idd.formula,idd.last_value,idd.default_value,idd.IS_SHOW,idd.C_UOM_ID,(select cu.name from C_UOM CU where cu.c_uom_id=idd.c_uom_id) cuname from " +
				"Emes_DC_Input_Data DID,Emes_DC_Input_Data_Detail idd,Emeso_DC_Item di " +
				"where DID.EMES_DC_INPUT_DATA_ID = IDD.EMES_DC_INPUT_DATA_ID " +
				"and idd.emeso_dc_item_id = di.emeso_dc_item_id " +
				"and did.Emes_DC_Input_Data_id = ? order by idd.seq_no ";
		List<Map<String,Object>> columnList = dao.query(sql, mapSql.get("EMES_DC_INPUT_DATA_ID").toString());
		System.out.println(mapSql.get("EMES_DC_INPUT_PAGE_ID").toString());
		for(int i=0;i<columnList.size();i++){
			Map<String,Object> tmpMap = columnList.get(i);
			String save_column = String.valueOf(tmpMap.get("SAVE_COLUMN"));
			Object defaultValueObj = tmpMap.get("DEFAULT_VALUE");
			if(defaultValueObj != null){
				Object result = null;
				String defaultValue = String.valueOf(defaultValueObj);
				if(defaultValue.contains("SQL=")){//默认值为sql
					try {
						String tmpSql = defaultValue.replace("SQL=","");
						Map<String,Object> resultMap = null;
						if(tmpSql.indexOf("?") > -1){
							resultMap = dao.queryUnique(tmpSql,batchId);
						}else{
							resultMap = dao.queryUnique(tmpSql);
						}
						if(resultMap != null){
							result = resultMap.get(resultMap.keySet().toArray()[0]);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					result = defaultValue;
				}
				if(result != null && dataList != null && dataList.size() > 0){
					// 上面sql 排序方向更改的时候, 取datalist 中设置值应该要修改
					int size = 0;
					if("asc".equals(StringUtils.trim(order))) {
						size = dataList.size() - 1;
					}
					Map<String,Object> tmpDataMap = dataList.get(size);
					Object tmpDataObj = tmpDataMap.get(save_column);
					if(tmpDataObj == null){//值为空时，才初始化默认值
						tmpDataMap.put(save_column,result);//加载默认值
					}
				}
			}
		}
		msg.setData("dataList", dataList);
		msg.setData("columnList", columnList);
		msg.setData("key",mapSql.get("EMES_DC_INPUT_DATA_ID").toString());
		return msg;
	}
}
